# @Time : 2025/4/19 20:50
# @Author : ZhangQi
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import threading
import json
from datetime import datetime
from adb.device_manager import DeviceManager


class ADBGUIApp:
    def __init__(self, root):
        self.root = root
        self.device_manager = None
        self.command_history = []
        self.history_index = -1
        self.setup_style()
        self.setup_ui()
        self.refresh_devices()

    def setup_style(self):
        """配置界面样式"""
        self.style = ttk.Style()
        self.style.theme_use('vista')
        self.style.configure('TFrame', background='#F0F0F0')
        self.style.configure('TLabel', background='#F0F0F0', font=('微软雅黑', 9))
        self.style.configure('TButton', foreground='black', background='#4285F4',
                             font=('微软雅黑', 9), padding=6)
        self.style.map('TButton',
                       foreground=[('active', 'black'), ('!active', 'black')],
                       background=[('active', '#3367D6'), ('!active', '#4285F4')])
        self.style.configure('Status.TLabel', font=('微软雅黑', 10, 'bold'))
        # 统一高度配置
        self.style.configure('TButton',
                             padding=(6, 3),  # 垂直padding控制高度
                             font=('微软雅黑', 9))

        self.style.configure('TEntry',
                             padding=(5, 3),  # 输入框padding
                             font=('Consolas', 11))

    def setup_ui(self):
        """初始化界面组件"""
        self.root.title("ADB智能控制助手 v2.0")
        self.root.geometry("1000x720")
        self.root.minsize(800, 600)

        # 主容器
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 设备控制面板
        control_frame = ttk.LabelFrame(main_frame, text="设备管理")
        control_frame.pack(fill=tk.X, pady=5)

        # 设备选择组件
        self.device_combobox = ttk.Combobox(
            control_frame,
            state="readonly",
            font=('微软雅黑', 9),
            width=25
        )
        self.device_combobox.pack(side=tk.LEFT, padx=5)

        # 操作按钮组
        btn_frame = ttk.Frame(control_frame)
        btn_frame.pack(side=tk.LEFT)

        self.refresh_btn = ttk.Button(
            btn_frame,
            text="刷新设备",
            command=self.refresh_devices,
            width=10
        )
        self.refresh_btn.pack(side=tk.LEFT, padx=2)

        self.connect_btn = ttk.Button(
            btn_frame,
            text="连接设备",
            command=self.connect_device,
            width=10
        )
        self.connect_btn.pack(side=tk.LEFT, padx=2)

        # 状态显示
        self.status_icon = ttk.Label(control_frame, text="●", font=('微软雅黑', 12))
        self.status_icon.pack(side=tk.LEFT, padx=5)
        self.status_label = ttk.Label(control_frame, style='Status.TLabel')
        self.status_label.pack(side=tk.LEFT)

        # 指令输入面板
        input_frame = ttk.LabelFrame(main_frame, text="指令输入")
        input_frame.pack(fill=tk.X, pady=5)

        self.cmd_entry = ttk.Entry(input_frame, font=('Consolas', 11))
        self.cmd_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.cmd_entry.bind("<Return>", lambda e: self.execute_command())
        self.cmd_entry.bind("<Up>", self.history_navigation)
        self.cmd_entry.bind("<Down>", self.history_navigation)

        self.send_btn = ttk.Button(
            input_frame,
            text="发送指令 (Enter)",
            command=self.execute_command,
            width=15
        )
        self.send_btn.pack(side=tk.RIGHT)

        # 结果展示面板
        result_frame = ttk.LabelFrame(main_frame, text="执行结果")
        result_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        self.result_area = scrolledtext.ScrolledText(
            result_frame,
            wrap=tk.WORD,
            font=('Consolas', 10),
            padx=10,
            pady=10,
            undo=True
        )
        self.result_area.pack(fill=tk.BOTH, expand=True)
        self.init_text_tags()

        # 历史记录面板
        history_frame = ttk.LabelFrame(main_frame, text="历史指令 (双击选择)")
        history_frame.pack(fill=tk.X, pady=5)
        self.history_listbox = tk.Listbox(
            history_frame,
            height=4,
            selectbackground='#D1E7F5',
            selectforeground='#000000',
            selectmode=tk.SINGLE,
            font=('Consolas', 9)
        )
        self.history_listbox.pack(fill=tk.X)
        self.history_listbox.bind("<Double-Button-1>", self.load_history)

        # 进度条
        self.progress = ttk.Progressbar(
            main_frame,
            mode='indeterminate',
            length=200
        )

    def init_text_tags(self):
        """初始化文本标签样式"""
        tags_config = {
            'timestamp': {'foreground': '#888888'},
            'success': {'foreground': '#009944'},
            'error': {'foreground': '#E74C3C'},
            'command': {'foreground': '#2C3E50', 'font': ('Consolas', 10, 'bold')},
            'response': {'font': ('Consolas', 10)}
        }
        for tag, config in tags_config.items():
            self.result_area.tag_config(tag, **config)

    def refresh_devices(self):
        """刷新设备列表"""

        def _refresh():
            try:
                devices_info = DeviceManager().get_connected_devices()
                devices = [d['device_id'] for d in devices_info.get('devices', [])]
                self.root.after(0, lambda: self.update_device_list(devices))
            except Exception as e:
                self.root.after(0, lambda: messagebox.showerror(
                    "刷新错误",
                    f"获取设备失败: {str(e)}"
                ))

        threading.Thread(target=_refresh, daemon=True).start()

    def update_device_list(self, devices):
        """更新设备下拉框"""
        self.device_combobox['values'] = devices
        if devices:
            self.device_combobox.current(0)
            self.update_status("检测到可用设备", '#4285F4')
        else:
            self.update_status("无可用设备", '#E74C3C')

    def connect_device(self):
        """连接选定设备"""
        device_id = self.device_combobox.get()
        if not device_id:
            messagebox.showwarning("选择错误", "请先选择要连接的设备")
            return

        def _connect():
            try:
                self.show_progress(True)
                self.device_manager = DeviceManager(device_id=device_id)
                self.root.after(0, lambda: self.update_status(
                    f"已连接: {device_id}",
                    '#27AE60'
                ))
                self.root.after(0, lambda: self.append_result(
                    f"✅ 设备 {device_id} 连接成功！\n支持指令示例：\n"
                    "1. 点击登录按钮\n2. 输入用户名test\n"
                    "3. 滑动[100,200]->[300,400]\n4. 执行淘宝Monkey测试500次",
                    'success'
                ))
            except Exception as e:
                self.root.after(0, lambda: self.update_status(
                    f"连接失败: {str(e)}",
                    '#E74C3C'
                ))
                self.root.after(0, lambda: messagebox.showerror(
                    "连接错误",
                    f"无法连接设备: {str(e)}"
                ))
            finally:
                self.root.after(0, lambda: self.show_progress(False))

        threading.Thread(target=_connect, daemon=True).start()

    def execute_command(self):
        """执行指令"""
        if not self.device_manager:
            messagebox.showwarning("设备未连接", "请先连接设备再执行指令")
            return

        command = self.cmd_entry.get().strip()
        if not command:
            messagebox.showwarning("输入错误", "指令不能为空")
            return

        self.add_history(command)
        self.cmd_entry.delete(0, tk.END)
        self.show_progress(True)
        self.append_result(f"\n{self.get_timestamp()} ", 'timestamp', end="")
        self.append_result(f"执行指令: {command}", 'command')

        def _execute():
            try:
                result = self.device_manager.process_command(command)
                formatted = json.dumps(result, indent=2, ensure_ascii=False)
                self.append_result(f"\n✅ 执行成功:\n", 'success', end="")
                self.append_result(f"{formatted}\n", 'response')
            except Exception as e:
                self.append_result(f"\n❌ 执行失败: {str(e)}\n", 'error')
            finally:
                self.show_progress(False)

        threading.Thread(target=_execute, daemon=True).start()

    def update_status(self, text, color):
        """更新状态栏"""
        self.status_icon.config(foreground=color)
        self.status_label.config(text=text)

    def append_result(self, text, tag=None, end="\n"):
        """追加结果显示"""
        self.result_area.config(state=tk.NORMAL)
        self.result_area.insert(tk.END, text + end, tag)
        self.result_area.see(tk.END)
        self.result_area.config(state=tk.DISABLED)

    def add_history(self, command):
        """添加历史记录"""
        if command not in self.command_history:
            self.command_history.append(command)
            self.history_listbox.insert(0, command)
            if self.history_listbox.size() > 10:
                self.history_listbox.delete(10, tk.END)

    def load_history(self, event):
        """加载历史记录到输入框"""
        selection = self.history_listbox.curselection()
        if selection:
            self.cmd_entry.delete(0, tk.END)
            self.cmd_entry.insert(0, self.history_listbox.get(selection[0]))

    def history_navigation(self, event):
        """历史指令导航"""
        if event.keysym == 'Up' and self.command_history:
            self.history_index = min(self.history_index + 1, len(self.command_history) - 1)
        elif event.keysym == 'Down' and self.history_index > -1:
            self.history_index = max(self.history_index - 1, -1)

        if self.history_index == -1:
            self.cmd_entry.delete(0, tk.END)
        else:
            self.cmd_entry.delete(0, tk.END)
            self.cmd_entry.insert(0, self.command_history[::-1][self.history_index])

    def show_progress(self, show=True):
        """显示/隐藏进度条"""
        if show:
            self.progress.pack(pady=5)
            self.progress.start()
            self.send_btn.config(state=tk.DISABLED)
            self.connect_btn.config(state=tk.DISABLED)
        else:
            self.progress.stop()
            self.progress.pack_forget()
            self.send_btn.config(state=tk.NORMAL)
            self.connect_btn.config(state=tk.NORMAL)

    def get_timestamp(self):
        """获取当前时间戳"""
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


if __name__ == "__main__":
    root = tk.Tk()
    try:
        root.iconbitmap('adb_icon.ico')
    except Exception as e:
        print(f"图标加载失败: {str(e)}")
    app = ADBGUIApp(root)
    root.mainloop()